package com.bjpowernode.controller;

import com.bjpowernode.entity.TClue;
import com.bjpowernode.entity.TCustomer;
import com.bjpowernode.query.CustomerQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class CustomerController {

    @Resource
    private CustomerService customerService;

    @PostMapping(value = "/api/customer")
    public R convertCustomer(@RequestBody CustomerQuery customerQuery) {
        boolean convert = customerService.convertCustomer(customerQuery);
        return convert ? R.OK() : R.FAIL();
    }

    @GetMapping(value = "/api/customers")
    public R customerByPage(@RequestParam(value = "current", required = false) Integer current) {
        // required = false 表示current参数可以传，也可以不传，也就是current参数可以是空的；
        // required = true 表示current参数必须传，不传会报错；
        if (current == null) {
            current = 1;
        }
        PageInfo<TCustomer> pageInfo = customerService.getCustomerPage(current);
        return R.OK(pageInfo);
    }

    @GetMapping(value = "/api/customer/{customerId}")
    public R customerDetail(@PathVariable(value = "customerId") Integer customerId) {
        TCustomer tCustomer = customerService.getCustomerById(customerId);
        return R.OK(tCustomer);
    }

    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(HttpServletResponse response,
                            @RequestParam(value = "ids", required = false) String ids) throws IOException {
        //对response要做一些设置
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //内容部署，附件
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + System.currentTimeMillis() + ".xlsx");

        List<String> idList = null;
        if (StringUtils.hasText(ids)) {
            idList = Arrays.asList(ids.split(","));
        }
        customerService.exportExcel(response.getOutputStream(), idList);
    }
}
